using ERPBackend.Data;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace ERPBackend.Services
{
    public class SupplierService : ISupplierService
    {
        private readonly ApplicationDbContext _context;

        public SupplierService(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<IEnumerable<Supplier>> GetAllSuppliersAsync()
        {
            return await _context.Suppliers.ToListAsync() ?? Enumerable.Empty<Supplier>();
        }

        public async Task<int> GetTotalSuppliersAsync()
        {
            return await _context.Suppliers.CountAsync();
        }

        public async Task<IEnumerable<Supplier>> GetSuppliersPagedAsync(int page, int pageSize)
        {
            // 计算跳过的记录数
            int skip = (page - 1) * pageSize;
            // 返回分页后的结果
            return await _context.Suppliers
                .OrderBy(s => s.SupplierCode)
                .Skip(skip)
                .Take(pageSize)
                .ToListAsync() ?? Enumerable.Empty<Supplier>();
        }

        public async Task<Supplier?> GetSupplierByIdAsync(int id)
        {
            return await _context.Suppliers.FindAsync(id);
        }

        public async Task<Supplier?> GetSupplierByCodeAsync(string supplierCode)
        {
            return await _context.Suppliers
                .FirstOrDefaultAsync(s => s.SupplierCode == supplierCode);
        }

        public async Task<Supplier> CreateSupplierAsync(Supplier supplier)
        {
            // 检查供应商编码是否已存在
            var existingSupplier = await _context.Suppliers
                .FirstOrDefaultAsync(s => s.SupplierCode == supplier.SupplierCode);
            if (existingSupplier != null)
            {
                throw new ArgumentException("供应商编码已存在");
            }

            _context.Suppliers.Add(supplier);
            await _context.SaveChangesAsync();
            return supplier;
        }

        public async Task<bool> UpdateSupplierAsync(Supplier supplier)
        {
            // 检查供应商是否存在
            var existingSupplier = await _context.Suppliers.FindAsync(supplier.Id);
            if (existingSupplier == null)
            {
                return false;
            }

            // 检查供应商编码是否已被其他供应商使用
            if (existingSupplier.SupplierCode != supplier.SupplierCode &&
                await _context.Suppliers.AnyAsync(s => s.SupplierCode == supplier.SupplierCode))
            {
                throw new ArgumentException("供应商编码已被使用");
            }

            // 更新属性
            existingSupplier.SupplierCode = supplier.SupplierCode;
            existingSupplier.SupplierName = supplier.SupplierName;
            existingSupplier.ContactPerson = supplier.ContactPerson;
            existingSupplier.Phone = supplier.Phone;

            existingSupplier.Address = supplier.Address;
            existingSupplier.Status = supplier.Status;
            existingSupplier.Notes = supplier.Notes;

            _context.Entry(existingSupplier).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteSupplierAsync(int id)
        {
            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return false;
            }

            // 检查是否有相关的联系人
            var hasContacts = await _context.SupplierContacts
                .AnyAsync(sc => sc.SupplierId == id);
            if (hasContacts)
            {
                // 实际业务中可能需要先删除联系人或提示用户
                return false;
            }

            // 检查是否有相关的资质
            var hasQualifications = await _context.SupplierQualifications
                .AnyAsync(sq => sq.SupplierId == id);
            if (hasQualifications)
            {
                // 实际业务中可能需要先删除资质或提示用户
                return false;
            }

            _context.Suppliers.Remove(supplier);
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ChangeSupplierStatusAsync(int id, byte status)
        {
            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return false;
            }

            supplier.Status = status;
            _context.Entry(supplier).State = EntityState.Modified;
            await _context.SaveChangesAsync();
            return true;
        }
    }
}